<template>
    <el-container>
        <el-main class="wrapper">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{'min-height': mainHeight+'px'}">
                <div class="panel-body">
                    <div class="btn-group" style="margin-bottom: 15px">
                        <el-button @click="create" type="primary" icon="fa fa-plus"
                                   size="small"> 新增
                        </el-button>
                        <el-button @click="list" type="primary" icon="fa fa-refresh"
                                   size="small"> 刷新
                        </el-button>
                        <el-button @click="toggleSelection(tableData,multipleSelection)" type="primary" icon="fa fa-toggle-on"
                                   size="small"> 反选
                        </el-button>
                        <el-button @click="deleteSelection(multipleSelection)" type="primary" icon="fa fa-trash"
                                   size="small"> 批量删除
                        </el-button>
                        <el-tag type="success">可推送预览数量：{{pageData.count_formid}}</el-tag>
                    </div>
                    <div class="bh-btn-group">
                        <div class="bh-search">
                            <el-input  size="medium" placeholder="请输入视频名称" v-model="search.title" class="input-with-select">
                                <el-button slot="append" icon="el-icon-search" @click="goSearch"></el-button>
                            </el-input>
                        </div>
                        <div class="bh-search">
                            <el-date-picker
                                    v-model="dateValue"
                                    align="right"
                                    type="daterange"
                                    unlink-panels
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    :picker-options="pickerOptions1" @change="pickerChange">
                            </el-date-picker>
                        </div>
                        <div class="bh-search" v-if="user && user.role_id == 1"  style="width: 140px">
                            <el-select size="medium" v-model="search.userid" placeholder="管理员">
                                <el-option label="管理员(全部)" value=""></el-option>
                                <el-option v-for="(manage,index) in manages" :key="index" :label="manage" :value="index"></el-option>
                            </el-select>
                        </div>
                        <div class="bh-search" style="width: 140px">
                            <el-select size="medium" v-model="search.hot" placeholder="热门(全部)">
                                <el-option label="热门(全部)" value=""></el-option>
                                <el-option v-for="(hot1,index) in hot" :key="index" :label="hot1" :value="index"></el-option>
                            </el-select>
                        </div>
                        <div class="bh-search" style="width: 140px">
                            <el-select size="medium" v-model="search.lock" placeholder="锁定(全部)">
                                <el-option label="锁定(全部)" value=""></el-option>
                                <el-option v-for="(lock1,index) in lock" :key="index" :label="lock1" :value="index"></el-option>
                            </el-select>
                        </div>
                        <div class="bh-search" style="width: 140px">
                            <el-select size="medium" v-model="search.sort" placeholder="默认排序">
                                <el-option label="默认排序" value=""></el-option>
                                <el-option label="浏览量" value="1"></el-option>
                                <el-option label="分享量" value="2"></el-option>
                            </el-select>
                        </div>
                    </div>
                    <el-table v-loading="loading"
                              element-loading-text="努力加载中..."
                              element-loading-spinner="el-icon-loading"
                              @selection-change="handleSelectionChange"
                              ref="multipleTable"
                              tooltip-effect="dark"
                              :data="tableData" :border="true" style="width: 100%">
                        <el-table-column type="selection" width="35px"></el-table-column>
                        <el-table-column prop="id" label="编号" width="80px"></el-table-column>
                        <el-table-column prop="title" label="标题" width="300px"></el-table-column>
                        <el-table-column prop="thumb" label="背景图" width="120px">
                            <template slot-scope="scope">
                                <el-popover
                                        placement="top"
                                        trigger="click">
                                    <img :src="scope.row.thumb" />
                                    <el-button slot="reference" style="border: none;height: 55px;padding: 0">
                                        <img :src="scope.row.thumb" style="height: 80px;width: 100px"/>
                                    </el-button>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="分类" width="100px"></el-table-column>
                        <el-table-column prop="nickname" label="管理员" width="100px"></el-table-column>
                        <el-table-column prop="share" label="有效分享" width="100px"></el-table-column>
                        <el-table-column prop="view" label="浏览量" width="100px"></el-table-column>
                        <el-table-column prop="pre" label="占比" width="100px"></el-table-column>
                        <el-table-column prop="lock" label="锁定" width="80px">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.lock == 0">否</el-tag>
                                <el-tag v-if="scope.row.lock == 1" type="danger">是</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="hot" label="热门" width="80px">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.hot == 0">否</el-tag>
                                <el-tag v-if="scope.row.hot == 1" type="danger">是</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="created_at" label="时间" width="150px">
                            <template slot-scope="scope">{{ scope.row.created_at ? moment(scope.row.created_at).format('YYYY-MM-DD HH:mm') : ''}}</template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <!--<el-button type="primary" size="mini" @click="edit(scope.row)" icon="fa fa-edit" plain>-->
                                <el-button type="primary" size="mini" @click="edit(scope.row.id)" icon="fa fa-edit" plain>
                                    编辑
                                </el-button>
                                <el-button icon="fa fa-trash" @click="destory(scope.row)" type="danger" size="mini" plain> 删除
                                </el-button>
                                <el-button icon="fa fa-eye" @click="phoneView(scope.row.id)" type="success" size="mini" plain> 预览
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <div class="pagination-total">共 <em>{{pageData.total}}</em> 篇文章</div>
                        <el-pagination  v-if="!loading && pageData && pageData.last_page > 1" background layout="prev, pager, next, jumper"
                                        :page-size="pageData.per_page"
                                        :total="pageData.total" :current-page="pageData.current_page"
                                        @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </div>
            </section>
        </el-main>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {ArticleList, ArticleUpdate, ArticleDestory,ManageAll,ArticlePush,ArticleDestoryAll} from '../../utils/axios';
    import {formatDate} from '../../utils/date';
    export default {
        components: {vBreadcrumb},
        data() {
            return {
                breadcumb: [{name: "文章管理"},],
                tableData: [],//列表数据
                pageData: [],//分页数据
                search: {page: null,title:'',userid:'',hot:'',lock:'',sort:"",start:null,end:null},//筛选
                manages:[],
                hot:['否','是'],
                lock:['否','是'],
                //日期筛选
                pickerOptions1: {
                    shortcuts: [{
                        text: '所有',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(0);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '今天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '对比昨天',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                dateValue: '',
                multipleSelection: [],
            }
        },
        activated() {
            this.$store.dispatch('setActive', '/article');
            this.list();
            ManageAll().then((response) => {
                if (response.code) {
                    this.$message.error(response.msg);
                } else {
                    this.manages = response.data;
                }
            })
        },
        //富文本字符串方法
        computed: {
            ...mapGetters(['active', 'mainHeight', 'loading', 'upload','user']),
        },
        methods: {
            goSearch(){
                this.search.page = 1;
                this.list();
            },
            //分页
            handleCurrentChange(val) {
                this.search.page = val;
                this.list();
            },
            //获取列表
            list() {
                //对象的赋值是拷贝new处一个对象来操作
                let obj = this.search
                let newObj = {};
                for (let elements in obj) {
                    newObj[elements] = obj[elements];
                }
                if(this.search.hot===null||this.search.hot===''||this.search.hot==='undefined'){
                    delete newObj.hot
                }
                this.$store.dispatch('setLoading', true);
                ArticleList({params: newObj}).then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$store.dispatch('setLoading', false);
                        this.tableData = response.data.data;
                        this.pageData = response.data;
                    }
                })
            },
            //编辑
            create() {
                this.$router.push({name:'ArticleUpdate'})
            },
            //编辑
            edit(id) {
                this.$router.push({name:'ArticleUpdate',params:{id:id}})
            },
            //手机预览
            phoneView(id){
                this.$confirm('确定要推送模板消息到手机查看吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    ArticlePush({id: id}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.$message.success(response.msg);
                            this.list();
                        }
                    });
                }).catch(() => {
                });
            },
            //删除
            destory(row) {
                console.log(row);
                if(row.lock === 1){
                    this.$message.error('文章已锁定，禁止删除！');
                    return false;
                }
                this.$confirm('确定要删除该文章信息吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    ArticleDestory({params: {id: row.id}}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                        }
                    });
                }).catch(() => {
                });
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
            },
            //选择
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //反选
            toggleSelection(rows,selects){
                let rowsSet = new Set(rows);
                let selectsSet = new Set(selects);
                // 差集
                let differenceNew = Array.from(new Set(rows.concat(selects).filter(v => rowsSet.has(v) && !selectsSet.has(v))));
                this.$refs.multipleTable.clearSelection();
                differenceNew.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            },
            //批量删除
            deleteSelection(selects){
                var that = this;
                this.$confirm('此操作将永久删除选中行, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var ids = [];
                    for(var i=0;selects.length>i;i++){
                        ids.push(selects[i].id);
                    }
                    ArticleDestoryAll({
                        params:{data:ids}
                    }).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                            that.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        }
                    });
                }).catch(() => {});
            },
            //时间筛选
            pickerChange() {
                if(this.dateValue){
                    var dateArr = this.dateValue;
                    this.search.start = formatDate(dateArr[0], 'yyyy-MM-dd');
                    this.search.end = formatDate(dateArr[1], 'yyyy-MM-dd');
                }else {
                    this.search.start = null;
                    this.search.end = null;
                }
            }
        },
    }
</script>

